package com.imooc.infra.repository;

import com.imooc.business.domain.Calculate;
import com.imooc.infra.mapping.CalculateMapping;
import com.imooc.infra.repository.entity.TDataCenterCalculate;
import com.imooc.infra.repository.entity.TDataCenterCollect;
import com.imooc.infra.repository.service.ITDataCenterCalculateService;
import lombok.Setter;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author Tim
 * @Description:
 * @Version 1.0
 */
@Repository
public class CalculateRepository {

    @Setter(onMethod_ = @Autowired)
    private ITDataCenterCalculateService calculateService;

    @Setter(onMethod_ = @Autowired)
    private CalculateMapping calculateMapping;

    /**
     * 根据规则id查询列表
     *
     * @param ruleId
     * @return
     */
    public List<Calculate> listByRuleId(Long ruleId) {
        List<TDataCenterCalculate> calculates = calculateService.listByRuleId(ruleId);
        return calculates.stream().map(calculateMapping::toVo).collect(Collectors.toList());
    }

    public List<Calculate> saveCalculate(Long ruleId, List<Calculate> calculates) {
        List<TDataCenterCalculate> entityList = calculates.stream().map(calculateMapping::toEntity).
                peek(collect -> collect.setRuleId(ruleId)).collect(Collectors.toList());
        boolean saveBatch = calculateService.saveBatch(entityList);
        if (saveBatch) {
            return entityList.stream().map(calculateMapping::toVo).collect(Collectors.toList());
        }
        return Lists.newArrayList();
    }

    public Calculate getByRuleIdAndEnName(Long ruleId, String enName) {
        TDataCenterCalculate calculate =  calculateService.getByRuleIdAndEnName(ruleId, enName);
        return Optional.ofNullable(calculate).map(calculateMapping::toVo).orElse(null);
    }
}
